﻿using System.Drawing;
using System.Drawing.Imaging;
using OpenTK.Graphics.OpenGL;
using PixelFormat = System.Drawing.Imaging.PixelFormat;

namespace Chimp.Core
{
    public class ChimpTextureDepth : ChimpTexture
    {
        public ChimpTextureDepth(int width, int height)
        {
            var TextureBitmap = new Bitmap(width, height);
            //get the data out of the bitmap
            BitmapData TextureData =
                TextureBitmap.LockBits(
                    new Rectangle(0, 0, TextureBitmap.Width, TextureBitmap.Height),
                    ImageLockMode.ReadOnly,
                    PixelFormat.Format24bppRgb
                    );

            //Code to get the data to the OpenGL Driver

            GL.Enable(EnableCap.Texture2D);
            //generate one texture and put its ID number into the "Texture" variable
            GL.GenTextures(1, out Texture);
            //tell OpenGL that this is a 2D texture
            GL.BindTexture(TextureTarget.Texture2D, Texture);

            //the following code sets certian parameters for the texture
            GL.TexEnv(TextureEnvTarget.TextureEnv,
                      TextureEnvParameter.TextureEnvMode,
                      (float) TextureEnvMode.Replace);
            GL.TexParameter(TextureTarget.Texture2D,
                            TextureParameterName.TextureMinFilter,
                            (float) TextureMinFilter.Linear);
            GL.TexParameter(TextureTarget.Texture2D,
                            TextureParameterName.TextureMagFilter,
                            (float) TextureMagFilter.Linear);

            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.DepthComponent, TextureBitmap.Width,
                          TextureBitmap.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.DepthComponent,
                          PixelType.UnsignedByte, TextureData.Scan0);

            Width = TextureBitmap.Width;
            Height = TextureBitmap.Height;
            Format = TextureFormat.Rgb;

            //load the data by telling OpenGL to build mipmaps out of the bitmap data
            //.Build2DMipmap(TextureTarget.Texture2D,
            //   (int)PixelInternalFormat.Three, TextureBitmap.Width, TextureBitmap.Height,
            // PixelFormat.Bgr, PixelType.UnsignedByte,
            // TextureData.Scan0
            // );

            //free the bitmap data (we dont need it anymore because it has been passed to the OpenGL driver
            TextureBitmap.UnlockBits(TextureData);
            GL.BindTexture(TextureTarget.Texture2D, 0);
            GL.Disable(EnableCap.Texture2D);
        }
    }
}